#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'hhuua'


import aiohttp
import asyncio
import json
from aiohttp import web


IpList = []
index = 0


async def handle_get_ip_list():
    global IpList
    json_data = json.dumps(IpList)
    return web.json_response(data=json_data)


async def handle_get_ip():
    global index
    global IpList
    if index >= len(IpList):
        index = 0
    ip = IpList[index]
    return web.json_response(data=ip)


async def fetch(session, url):
    async with session.get(url) as resp:
        data = await resp.text()
        return data


async def get_new_ip():
    async with aiohttp.ClientSession() as session:
        url = 'http://api.wandoudl.com/api/ip?app_key=b19916f24d1226d02e313f0fd01c303c&pack=216456&num=20&xy=1&type=2&lb=\r\n&mr=1&'
        resp = await fetch(session, url)
        resp_dic = json.loads(resp)
        ip_arr = []
        for ips in resp_dic['data']:
            ip_arr.append(ips['ip'])
        global IpList
        IpList = ip_arr


def start_get_ip():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(get_new_ip())


def start_ip_app():
    app = web.Application()
    app.add_routes([web.get('/getIpList', handle_get_ip_list),
                    web.get('/getIp', handle_get_ip)])

    web.run_app(app, port=5000)
#
# if __name__ == '__main__':
#     start_get_ip()
#     t = Timer(600, start_get_ip)
#     t.start()
#     web.run_app(app, port=5000)

